/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jastrzab.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import java.util.ArrayList;

/**
 *
 * @author Jastrzab
 */
public abstract class BindSevice extends Service {

	public static final int REGISTER_CLIENT = 0x1;
	public static final int REMOVE_CLIENT = 0x2;
	private final ArrayList<Messenger> mClients = new ArrayList<Messenger>();
	private final Messenger mMessenger = new Messenger(new ReciveHandler());

	@Override
	public IBinder onBind(Intent arg0) {
		return mMessenger.getBinder();
	}

	public void sendHandler(Message message) {
		if (!mClients.isEmpty()) {
			message.replyTo = mMessenger;
			for (int i = (mClients.size() - 1); i >= 0; i--) {
				try {
					mClients.get(i).send(message);
				} catch (RemoteException e) {
					mClients.remove(i);
				}
			}
		}
	}

	private final class ReciveHandler extends Handler {

		@Override
		public void handleMessage(Message message) {
			switch (message.what) {
				case REGISTER_CLIENT:
					mClients.add(message.replyTo);
					onAddActivity(mClients.size());
				break;
				case REMOVE_CLIENT:
					mClients.remove(message.replyTo);
					onRemoveActivity(mClients.size(), (Boolean) message.obj);
				break;
				default:
					onReciveHandler(message);
			}
		}

	}

	public void onAddActivity(int count) {

	};

	public void onRemoveActivity(int count, boolean finish) {

	};

	protected abstract void onReciveHandler(Message message);

}
